package com.appspot.aliga.persistence;

import java.util.List;

import com.appspot.aliga.League;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.util.DAOBase;

public class PersistenceService extends DAOBase {

	static {
		ObjectifyService.register(Match.class);
		ObjectifyService.register(Gameday.class);
		ObjectifyService.register(LeagueTableEntry.class);
	}

	public Key<Match> saveMatch(Match match) {
		Key<Match> key = ofy().put(match);
		return key;
	}

	public List<Match> findAllMatches() {
		return ofy().query(Match.class).list();
	}

	public Gameday getGameday(int leagueID, int gameday) {
		Gameday gd = ofy().query(Gameday.class).filter("leagueID", leagueID)
				.filter("day", gameday).get();
		return gd;
	}

	public Key<Gameday> saveGameday(Gameday gd) {
		return ofy().put(gd);
	}

	public List<Match> findMatches(int leagueID, int gameday) {
		List<Match> matches = ofy().query(Match.class).filter("leagueID",
				leagueID).filter("gameDay", gameday).list();

		return matches;
	}

	public List<Match> findMatches(int leagueID) {
		List<Match> matches = ofy().query(Match.class).filter("leagueID",
				leagueID).list();

		return matches;
	}

	public Match findMatch(int matchID) {
		return ofy().get(Match.class, new Long(matchID));
	}

	public List<Gameday> findGamedays(int leagueID) {
		List<Gameday> result = ofy().query(Gameday.class).filter("leagueID",
				leagueID).list();

		return result;
	}

	public void cleanDB() {
		List<Match> matches = ofy().query(Match.class).list();
		ofy().delete(matches);

		List<Gameday> gamedays = ofy().query(Gameday.class).list();
		ofy().delete(gamedays);
	}

	public void saveLeagueTableForLeague(League league,
			List<LeagueTableEntry> entries) {
		// delete old entries for league
		List<LeagueTableEntry> les = ofy().query(LeagueTableEntry.class)
				.filter("leagueID", league.getId()).list();
		ofy().delete(les);

		ofy().put(entries);

	}

	public List<LeagueTableEntry> findLeagueTableEntries(int leagueID) {
		List<LeagueTableEntry> les = ofy().query(LeagueTableEntry.class)
				.filter("leagueID", leagueID).list();
		return les;
	}
}
